package cn.edu.jxau.core.util.mail;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

import com.sun.mail.util.MailSSLSocketFactory;

/**
 * 本类只有这么一个方法，用来发邮件！邮件发送工具
 * MailUtils
 * @author zclong 2017年8月4日
 */
public class MailUtils {
    
    /**
     * 开启SSL协议(安全协议)
     * @zclong
     * @2017年8月4日
     * @ReturnType: void
     * @param prop
     */
    private static void enableSSL(Properties prop) {
        try {
            MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
            mailSSLSocketFactory.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);
        } catch (GeneralSecurityException e) {
            throw new RuntimeException(e);
        }
    }
    /**
     * 创建发送邮件的会话
     * Session : 如果得到了他，表示已经和服务器连接上了，与Connection相似
     * @zclong
     * @2017年8月4日
     * @ReturnType: Session
     * @param host
     * @param username
     * @param password
     * @return
     */
    public static Session createSession(String host, final String username, final String password, boolean ssl_enable) {
        Properties prop = new Properties();
        prop.put("mail.host", host);// 指定主机
        prop.put("mail.smtp.auth", "true");// 指定验证为true
        prop.put("mail.transport.protocol", "smtp");// 选择协议
        
        //如果ssl_enable为true,开启SSL协议
        if(ssl_enable) {
            enableSSL(prop);
        }
        
        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        };
        
        // 获取session对象
        return Session.getInstance(prop, auth);
    }
    
    /**
     * 发送指定的邮件
     * @param mail
     */
    public static void send(Session session, final Mail mail) throws MessagingException, IOException {

        MimeMessage msg = new MimeMessage(session);// 创建邮件对象
        msg.setFrom(new InternetAddress(mail.getFrom()));// 设置发件人
        msg.addRecipients(RecipientType.TO, mail.getToAddress());// 设置收件人

        // 设置抄送
        String cc = mail.getCcAddress();
        if (!cc.isEmpty()) {
            msg.addRecipients(RecipientType.CC, cc);
        }

        // 设置暗送
        String bcc = mail.getBccAddress();
        if (!bcc.isEmpty()) {
            msg.addRecipients(RecipientType.BCC, bcc);
        }

        msg.setSubject(mail.getSubject());// 设置主题

        MimeMultipart parts = new MimeMultipart();// 创建部件集对象

        MimeBodyPart part = new MimeBodyPart();// 创建一个部件
        part.setContent(mail.getContent(), "text/html;charset=utf-8");// 设置邮件文本内容
        parts.addBodyPart(part);// 把部件添加到部件集中

        ///////////////////////////////////////////

        // 添加附件
        List<AttachBean> attachBeanList = mail.getAttachs();// 获取所有附件
        if (attachBeanList != null) {
            for (AttachBean attach : attachBeanList) {
                MimeBodyPart attachPart = new MimeBodyPart();// 创建一个部件
                attachPart.attachFile(attach.getFile());// 设置附件文件
                attachPart.setFileName(MimeUtility.encodeText(attach.getFileName()));// 设置附件文件名
                String cid = attach.getCid();
                if (cid != null) {
                    attachPart.setContentID(cid);
                }
                parts.addBodyPart(attachPart);
            }
        }

        msg.setContent(parts);// 给邮件设置内容
        msg.setSentDate(new Date());// 设置发送时间
        
        Transport transport = session.getTransport();
        transport.connect();
        // 发邮件
        transport.sendMessage(msg, msg.getRecipients(RecipientType.TO));
        transport.close();

        // Transport.send(msg);
    }
}
